<template>
  <div class="sign">
    <!-- 导航栏 -->
    <div class="tab-bar">
      <van-nav-bar left-arrow @click-left="$router.go(-1)" :border="false">
        <span class="headline" slot="title">代签文件.PDF</span>
      </van-nav-bar>
      <span class="company">{{ title }}</span>
    </div>
    <!-- 合同模块 -->
    <div class="contract-img">
      <div
        class="doc-page-content"
        :id="index + 1"
        v-for="(item, index) in contractImg"
        :key="index"
      >
        <img :src="'data:image/png;base64,' + item" alt="" />
      </div>
    </div>
    <!-- 底部按钮 -->
    <div class="sign-button">
      <span class="button-span" @click="signature">
        <van-icon
          class="icon-sketching"
          class-prefix="iconfont iconshouxieqianmingicon"
        />
        手写签名
      </span>
      <span class="button-span" @click="seal = true">
        <van-icon
          class="icon-sketching"
          class-prefix="iconfont iconweibiaoti--"
        />
        盖章
      </span>
      <van-button class="myButton" type="info" @click="immediately"
        >立即签署</van-button
      >
    </div>
    <!-- 手绘弹出层 -->
    <van-popup
      class="show-handwritten"
      v-model="ShowHandwritten"
      position="bottom"
      :style="{ height: '50%' }"
    >
      <div class="handwritten-head" @click="addHandwritten">
        <van-icon
          class="icon-handwritten"
          class-prefix="iconfont iconshouhuiqianmingicon"
        />
        直接手绘签名
      </div>
      <!-- 印章 -->
      <van-card
        centered
        class="handwritten-card"
        v-for="(item, index) in writeSignature.records"
        :key="index"
        @click="addDrag(item)"
      >
        <img slot="thumb" :src="item.sealImgData" alt="" />
        <span slot="desc">{{ item.sealName }}</span>
      </van-card>
    </van-popup>
    <!-- 盖章弹出窗 -->
    <van-popup class="seal" v-model="seal" position="bottom">
      <!-- 印章 -->
      <van-card
        centered
        title="合同专用章"
        desc="北京华信云盛科技有限公司"
        @click="addDrag"
      >
        <img slot="thumb" src="../../assets/公司印章.png" alt="" />
      </van-card>
      <van-card centered title="公章" desc="北京华信云盛科技有限公司">
        <img slot="thumb" src="../../assets/公司印章.png" alt="" />
      </van-card>
      <van-card centered title="公章" desc="北京华信云盛科技有限公司">
        <img slot="thumb" src="../../assets/公司印章.png" alt="" />
      </van-card>
    </van-popup>
    <!-- 签署校验 -->
    <van-popup
      round
      class="verify"
      v-model="verify"
      :close-on-click-overlay="false"
    >
      <div class="verify-box">
        <div class="verify-title">
          <span></span>
          签署校验
          <span></span>
        </div>
        <div class="verify-name">
          <span>请确认本人操作</span>
          <span>校验成功后即可完成文件签署</span>
        </div>
      </div>
      <van-form ref="sthForm">
        <van-field class="name-number" v-model="mobile" :readonly="true" />
        <van-field
          class="sms"
          center
          v-model="vcode"
          placeholder="请输入验证码"
        >
          <template #button>
            <van-button size="small" @click="getCode">获取验证码</van-button>
          </template>
        </van-field>
        <van-button class="btn-cancel" type="default" @click="verify = false"
          >取消</van-button
        >
        <van-button class="btn-confirm" type="default" @click="submitVerify"
          >确定</van-button
        >
      </van-form>
    </van-popup>
  </div>
</template>

<script>
import {
  addContractMessage,
  addContractPreview,
  addContractSignature,
  addContractAbstract
} from '@/api/contract'
import { sendSms } from '@/api/user'
import { setItem, getItem } from '@/utils/storage'
export default {
  data() {
    return {
      // 待签名文件
      fileList: [],
      // 合同详情
      contractAllInfo: {},
      // 展示第一个文件
      curFile: {
        contractId: '',
        fileId: '',
        filePath: '',
        filePages: []
      },
      title: '',
      // 合同图片
      contractImg: [],
      // 拖拽节流
      flags: false,
      // 手绘弹出层显示隐藏
      ShowHandwritten: false,
      // 印章弹出窗
      seal: false,
      // 合同被卷去的头部
      reel: 0,
      // 选择的base64印章
      fraglmg: '',
      // 校验弹框显示
      verify: false,
      // 手机号码
      mobile: '',
      // 手绘印章
      writeSignature: {},
      width: '',
      height: '',
      // 摘要
      contractId: '',
      pageNum: '',
      btnImg: '',
      // 鼠标的位置
      position: { x: 0, y: 0 },
      // 鼠标移动的距离
      nx: '',
      ny: '',
      // 盒子的位置
      dx: '',
      dy: '',
      // 盒子移动后的距离
      xPum: '',
      yPum: '',
      // 添加的盒子
      coordsData: [],
      // 印章信息
      coords: {
        pageNum: '',
        xcoord: '',
        ycoord: '',
        xpercent: '',
        ypercent: ''
      },
      authcWay: 2,
      // authcWay为1
      signsealPwd: '',
      // authcWay为2
      vcode: '',
      boxId: 0
    }
  },
  created() {
    if (this.$route.params.contractId) {
      setItem('contractId', this.$route.params.contractId)
    }
    this.contractId = this.$route.params.contractId || getItem('contractId')
    this.info()
    this.mobile = this.$store.state.userName.mobile
  },
  mounted() {
    this.bizNo = new Date().getTime()
  },
  methods: {
    async info() {
      try {
        await addContractMessage({ contractId: this.contractId }).then(res => {
          if (res.data.code !== '0') {
            return this.$toast.fail('图片获取失败!')
          }
          this.contractAllInfo = res.data.data
          this.title = this.contractAllInfo.contractBaseInfo.title

          // 待签名文件列表
          const tempFileArr = []
          this.contractAllInfo.signingFileInfoList.forEach(item => {
            const file = {
              fileId: item.fileId,
              fileName: item.fileName,
              filePath: item.filePath,
              filePages: item.filePages
            }
            tempFileArr.push(file)
          })
          this.fileList = tempFileArr

          // 展示第一个文件
          this.curFile.contractId = this.contractAllInfo.contractBaseInfo.contractId
          this.curFile.fileId = this.fileList[0].fileId
          this.curFile.filePath = this.fileList[0].filePath
          const pages = []
          for (var i = 0; i <= this.fileList[0].filePages; i++) {
            pages.push(i + 1)
          }
          this.curFile.filePages = pages
        })
        for (let i = 1; i < this.curFile.filePages.length; i++) {
          await addContractPreview({
            // contractId: this.curFile.contractId,
            filePath: this.curFile.filePath,
            pageNum: i
          }).then(res => {
            if (res.data.code !== '0') {
              return this.$toast.fail('图片获取失败!')
            }
            this.contractImg.push(res.data.data)
          })
        }
      } catch (error) {
        console.log(error)
      }
    },
    // 电子签名请求
    async signature() {
      this.ShowHandwritten = true
      try {
        await addContractSignature({
          idNumber: this.$store.state.userName.idNumber
        }).then(res => {
          console.log(res.data)
          if (res.data.code !== '0') {
            return this.$toast.fail('手写获取失败')
          }
          this.writeSignature = res.data.data
          if (this.writeSignature.records.length === 0) {
            this.$toast('没有手绘签名')
          }
        })
      } catch (error) {
        console.log(error)
      }
    },
    // 手写签名点击事件
    addHandwritten() {
      this.$router.push('/canvas')
    },
    // 选择印章
    addDrag(item) {
      this.seal = false
      this.ShowHandwritten = false
      this.btnImg = item.sealImgData
      const DIV = document.getElementById('1')
      this.height = DIV.offsetHeight
      this.width = DIV.offsetWidth
      const top = document.scrollTop || document.documentElement.scrollTop
      this.pageNum = Math.round(top / this.height) + 1
      this.coords.pageNum = this.pageNum
      const list = {
        id: this.boxId,
        pageNum: this.pageNum,
        xcoord: 0,
        ycoord: 0,
        xpercent: 0,
        ypercent: 100
      }
      this.coordsData.push(list)
      this.docCompCoverDroppableBind(item, this.boxId)
      this.boxId++
    },
    // 点击立即签署
    immediately() {
      if (this.btnImg === '') {
        return this.$toast('请先放置印章')
      }
      this.verify = true
    },
    // 表单提交事件
    async submitVerify() {
      if (this.vcode === '') {
        return this.$toast('请输入验证码')
      }
      var coords = []
      for (var key in this.coordsData) {
        var data = this.coordsData[key]
        var coord = {
          pageNum: data.pageNum,
          xcoord: data.xcoord,
          ycoord: data.ycoord,
          xpercent: data.xpercent,
          ypercent: data.ypercent
        }
        coords.push(coord)
      }

      if (coords.length === 0) {
        return this.$toast('至少指定一个盖章位置')
      }
      this.verify = false
      this.$toast.loading({
        message: '正在签署...',
        forbidClick: true
      })
      var param = {
        contractId: this.contractId,
        bizNo: this.bizNo,
        sealImg: this.btnImg.replace(/^data:image\/\w+;base64,/, ''),
        authcWay: this.authcWay,
        vcode: this.vcode,
        coords: coords
      }
      try {
        const { data: res } = await addContractAbstract(param)
        if (res.code !== '0') {
          return this.$toast.fail(res.data.msg)
        }
        this.$toast.success('签署成功')
        this.$router.push({
          name: 'authentication',
          params: { contractId: this.contractId }
        })
      } catch (error) {
        console.log(error)
      }
    },
    // 控件可拖拽
    down(moveDiv) {
      // const moveDiv = e.target
      this.flags = true

      // 当前元素的位置
      let touch
      if (event.touches) {
        touch = event.touches[0]
      } else {
        touch = event
      }
      // 鼠标的位置
      this.position.x = touch.clientX
      this.position.y = touch.clientY
      // 盒子的位置
      this.dx = moveDiv.offsetLeft
      this.dy = moveDiv.offsetTop
    },
    // 移动
    move(moveDiv) {
      // const moveDiv = e.target
      if (this.flags) {
        let touch
        if (event.touches) {
          touch = event.touches[0]
        } else {
          touch = event
        }
        // 获取鼠标移动的距离
        this.nx = touch.clientX - this.position.x
        this.ny = touch.clientY - this.position.y
        // 盒子移动
        this.xPum = this.dx + this.nx
        this.yPum = this.dy + this.ny
        // 添加限制：只允许在屏幕内拖动
        const maxWidth = document.body.clientWidth - moveDiv.offsetWidth // 屏幕宽度减去悬浮框宽高的一半
        const maxHeight = this.height - moveDiv.offsetHeight
        if (this.xPum < 0) {
          // 屏幕x限制
          this.xPum = 0
        } else if (this.xPum > maxWidth) {
          this.xPum = maxWidth
        }
        if (this.yPum < 0) {
          // 屏幕y限制
          this.yPum = 0
        } else if (this.yPum > maxHeight) {
          this.yPum = maxHeight
        }
        moveDiv.style.left = this.xPum + 'px'
        moveDiv.style.top = this.yPum + 'px'
        // 阻止页面的滑动默认事件
        window.addEventListener('touchmove', this.approve(event), {
          passive: false
        })
      }
    },
    // 浏览器默认行为
    approve(e) {
      e.preventDefault()
    },
    // 拖拽释放
    end(id) {
      const height = (100 - (this.yPum / this.height) * 100).toFixed(2)
      const widht = ((this.xPum / this.width) * 100).toFixed(2)
      this.coordsData.forEach(item => {
        if (item.id === id) {
          item.xpercent = widht
          item.ypercent = height
          item.xcoord = this.xPum
          item.ycoord = this.height - this.yPum
        }
      })
      this.flags = false
      // 移除页面默认行为
      window.removeEventListener('touchmove', this.approve)
    },
    // 创建可拖拽控件
    docCompCoverDroppableBind(item, id) {
      const that = this
      let width = 0
      let height = 0
      // 企业盖公章
      if (item.sealType === 1) {
        width = this.width * 0.190476
        height = width
      } else if (item.sealType === 2) {
        // 个人名章
        width = this.width * 0.095
        height = this.height * 0.048
      }
      // 建
      const span1 = document.createElement('span')
      span1.textContent = '删除'
      span1.className = 'found-span'
      span1.onclick = function() {
        const index = that.coordsData.findIndex(item => item.id === id)
        that.coordsData.splice(index, 1)
        const box = document.getElementById(`${item.id}${id}`)
        box.remove()
      }
      const span2 = document.createElement('span')
      span2.textContent = '换章'
      span2.className = 'found-span'
      span2.onclick = function() {
        that.ShowHandwritten = true
        const index = that.coordsData.findIndex(item => item.id === id)
        that.coordsData.splice(index, 1)
        const box = document.getElementById(`${item.id}${id}`)
        box.remove()
      }
      const span3 = document.createElement('span')
      span3.textContent = '修改'
      span3.className = 'found-span'
      // 按钮
      const boxdiv = document.createElement('div')
      boxdiv.className = 'fixed-span'
      boxdiv.style.height = '32px'
      boxdiv.style.width = '141px'
      boxdiv.style.top = '-39px'
      boxdiv.style.left = -(71 - width / 2) + 'px'
      boxdiv.removeEventListener('touchstart', that.down)

      boxdiv.appendChild(span1)
      boxdiv.appendChild(span2)
      boxdiv.appendChild(span3)

      // 图片
      const sealImgEle = `<img src="${item.sealImgData}" style="width:${width -
        1}px;height:${height - 1}px;" />`
      // 盒子
      const div = document.createElement('div')
      div.innerHTML = sealImgEle
      div.id = `${item.id}${id}`
      div.style.width = width + 'px'
      div.style.height = height + 'px'
      div.style.zIndex = '4'
      div.className = 'control-signseal'
      div.ontouchstart = function() {
        that.down(div)
      }
      // div.addEventListener(
      //   'touchstart',
      //   function(e) {
      //     console.log(e.target)
      //     that.down(e)
      //   },
      //   false
      // )
      div.ontouchmove = function() {
        that.move(div)
      }
      // div.addEventListener(
      //   'touchmove',
      //   function() {
      //     that.move(div)
      //   },
      //   false
      // )
      div.ontouchend = function() {
        that.end(id)
      }
      // div.addEventListener(
      //   'touchend',
      //   function() {
      //     that.end(id)
      //   },
      //   false
      // )
      div.appendChild(boxdiv)
      const addSeal = document.getElementById(this.pageNum)
      addSeal.appendChild(div)
    },
    // 获取验证码
    async getCode() {
      try {
        const { data: res } = await sendSms(this.mobile)
        if (res.code !== '0') {
          return this.$toast.fail('发送短信失败')
        }
      } catch (error) {
        console.log(error)
      }
    }
  }
}
</script>

<style scoped lang="less">
.sign {
  padding: 168px 0 120px;
  .tab-bar {
    position: fixed;
    top: 0;
    left: 0;
    width: 100%;
    height: 88px;
    background-color: #fff;
    z-index: 33;
    .van-nav-bar {
      .headline {
        font-size: 34px;
        font-weight: bold;
      }
      /deep/.van-icon {
        font-size: 40px;
        color: #101010;
      }
    }
    /deep/.van-nav-bar__left {
      padding-left: 23px;
    }
    .company {
      font-size: 26px;
      display: block;
      box-sizing: border-box;
      height: 80px;
      line-height: 80px;
      padding-left: 41px;
      border-bottom: 1px solid #e0e0e0;
      color: #2c2c2c;
      background-color: #fff;
    }
  }
  // 按钮
  .sign-button {
    position: fixed;
    bottom: 0;
    left: 0;
    width: 100%;
    height: 120px;
    line-height: 120px;
    border-top: 1px solid #e0e0e0;
    background-color: #fff;
    .button-span {
      font-size: 24px;
      margin-left: 40px;
      .icon-sketching {
        font-size: 35px;
      }
      .iconfont {
        margin-right: 13px;
        vertical-align: middle;
      }
    }
    .myButton {
      position: absolute;
      width: 280px;
      height: 80px;
      right: 40px;
      top: 20px;
    }
  }
  // 合同
  .contract-img {
    height: 78.4vh;
    .doc-page-content {
      position: relative;
      img {
        display: block;
        width: 100%;
      }
      /deep/.control-signseal {
        position: absolute;
        top: 3px;
        bottom: 0;
        border: 1px dashed rgb(0, 175, 161);
        img {
          display: block;
        }
        .fixed-span {
          position: absolute;
          background-color: rgba(0, 0, 0, 0.4);
          border-radius: 10px;
          display: flex;
          justify-content: space-around;
          align-items: center;
          .found-span {
            font-size: 28px;
            color: #fff;
          }
        }
      }
    }
  }

  // 手绘
  .show-handwritten {
    .handwritten-head {
      height: 100px;
      display: flex;
      justify-content: center;
      align-items: center;
      font-size: 28px;
      color: #2489f2;
      border-bottom: 1px solid #e4e4e4;
      .icon-handwritten {
        font-size: 30px;
        margin-right: 11px;
      }
    }
    .van-card:not(:first-child) {
      margin-top: 0;
    }
    .handwritten-card {
      .van-card__thumb {
        width: 200px;
        height: 168px;
        display: flex;
        flex-direction: column;
        justify-content: center;
        border-radius: 6px;
        img {
          width: 100%;
          height: 100%;
        }
      }
    }
  }
  .seal {
    height: 561px;
    .van-card__thumb {
      margin: 52px 52px 52px 100px !important;
    }
    .van-card__title {
      font-weight: bold;
      font-size: 30px;
      margin-bottom: 22px;
    }
    .van-card:not(:first-child) {
      margin-top: 0;
    }
  }
  // 底部按钮
  .van-card {
    padding: 0;
    background-color: #fff;
    border-bottom: 1px solid #e4e4e4;
    .van-card__thumb {
      margin: 61px 86px 61px 85px;
      img {
        width: 100%;
      }
    }
  }
  // 校验
  .verify {
    width: 560px;
    height: 561px;
    background-color: #fff;
    text-align: center;
    .verify-box {
      box-sizing: border-box;
      height: 234px;
      padding-top: 49px;
      .verify-title {
        font-size: 34px;
        margin-bottom: 23px;
        span {
          display: inline-block;
          height: 1px;
          width: 30px;
          border-bottom: 1px solid #000;
          margin: 0 18px;
          vertical-align: middle;
        }
      }
      .verify-name {
        display: flex;
        flex-direction: column;
        span:nth-child(1) {
          font-size: 30px;
          margin-bottom: 15px;
        }
        span:nth-child(2) {
          font-size: 26px;
          color: #999999;
        }
      }
    }
    .van-form {
      padding: 0 32px;
      .name-number {
        height: 84px;
        background-color: #f2f2f2;
        margin-bottom: 24px;
        border: 1px solid #dadada;
      }
      .sms {
        height: 84px;
        border: 1px solid #dadada;
        padding-right: 0;
        .van-button--small {
          width: 189px;
          height: 40px;
          font-size: 30px;
          vertical-align: middle;
          border-width: 0;
          border-left: 1px solid #dadada;
          color: #666666;
        }
      }
      .btn-cancel {
        position: absolute;
        left: 0;
        bottom: 0;
        width: 50%;
        border-right: 0;
      }
      .btn-confirm {
        width: 50%;
        position: absolute;
        right: 0;
        bottom: 0;
      }
    }
  }
}
</style>
